package com.jacobson.huobi.components.toptab;

import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;

import com.jacobson.core.widget.logger.Logger;
import com.jacobson.core.widget.logger.LoggerFactory;
import com.jacobson.huobi.Constants;
import com.jacobson.huobi.R;
import com.jacobson.huobi.common.constants.AlarmTypeConstant;
import com.jacobson.huobi.common.expansion.EntitiesExtKt;
import com.jacobson.huobi.entities.SymbolInfo;
import com.scwang.smartrefresh.layout.util.DensityUtil;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author WuChenZhong on 2019/7/19 16:48
 * @version 1.0.0
 */
public class TopTabContainer extends FrameLayout {
    private static final int POSITION_FAVORITE = 0;
    private static final int POSITION_ANALYSIS = 4;
    private Logger logger = LoggerFactory.INSTANCE.getLogger();
    private TabsData tabsData;
    private int[] numbers;
    private int[] bottomNumbers;
    private int selectedPosition;
    private LinearLayout tabContainer;
    private LinearLayout tipContainer;
    private OnItemSelectedListener onItemSelectedListener;
    private Map<String, Long> lastAlarmTs = new ConcurrentHashMap<>();

    public TopTabContainer(Context context) {
        super(context);
    }

    public TopTabContainer(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public TopTabContainer(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        LayoutInflater.from(getContext()).inflate(R.layout.view_top_tab_container, this, true);
        tabContainer = findViewById(R.id.tab_container);
        tipContainer = findViewById(R.id.tip_container);
        initView();
    }

    public int getSelectedPosition() {
        return selectedPosition;
    }

    public void setTabs(TabsData data) {
        setTabs(data, 0);
    }

    public void setTabs(TabsData data, int defaultPosition) {
        this.tabsData = data;
        this.numbers = new int[data.size()];
        this.bottomNumbers = new int[data.size()];
        Arrays.fill(this.numbers, 0);
        Arrays.fill(this.bottomNumbers, 0);
        selectedPosition = defaultPosition;
        initView();
        requestLayout();
        logger.d("TABS: " + data);
    }

    private void onSelectChanged(int position, String tab) {
        this.selectedPosition = position;
        this.numbers[this.selectedPosition] = 0;
        this.bottomNumbers[this.selectedPosition] = 0;
        refreshAllTabsExterior();
        if (this.onItemSelectedListener != null) {
            this.onItemSelectedListener.onItemSelected(position, tab);
        }
    }

    private void initView() {
        if (tabContainer == null) {
            return;
        }
        tabContainer.removeAllViews();
        if (this.tabsData == null || !this.tabsData.hasTab()) {
            return;
        }
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(DensityUtil.dp2px(60), LayoutParams.MATCH_PARENT);
        for (int i = 0; i < tabsData.size(); i++) {
            TextView textView = createTextView(tabsData.getTab(i), i);
            tabContainer.addView(textView, params);

            View tipView = createTipContainer(i);
//            View tipBottomView = createTipBottomContainer(i);
            tipContainer.addView(tipView, params);
//            tipContainer.addView(tipBottomView, params);
        }
        if (onItemSelectedListener != null) {
            onItemSelectedListener.onItemSelected(selectedPosition, tabsData.getTab(selectedPosition));
        }
        refreshAllTabsExterior();
    }

    public void selectedPosition(int position) {
        onSelectChanged(position, tabsData.getTab(position));
    }

    private View createTipContainer(int index) {
        TipView tipView = new TipView(getContext());
        tipView.setNumber(numbers[index], bottomNumbers[index]);
        return tipView;
    }


    private void refreshAllTabsExterior() {
        int childCount = tabContainer.getChildCount();
        if (childCount == 1) {
            setExteriorAtPosition(0, R.drawable.ic_tab_item_selected_only, R.color.tab_selected_text_color);
            return;
        }
        for (int i = 0; i < childCount; i++) {
            if (i == selectedPosition) {
                if (i == 0) {
                    setExteriorAtPosition(i, R.drawable.ic_tab_item_selected_first, R.color.tab_selected_text_color);
                } else if (i == childCount - 1) {
                    setExteriorAtPosition(i, R.drawable.ic_tab_item_selected_last, R.color.tab_selected_text_color);
                } else {
                    setExteriorAtPosition(i, R.drawable.ic_tab_item_selected, R.color.tab_selected_text_color);
                }
            } else {
                if (i == 0) {
                    if (i + 1 == selectedPosition) {
                        setExteriorAtPosition(i, R.drawable.ic_tab_item_normal_first_pre, R.color.tab_normal_text_color);
                    } else {
                        setExteriorAtPosition(i, R.drawable.ic_tab_item_normal_first, R.color.tab_normal_text_color);
                    }
                } else if (i == childCount - 1) {
                    setExteriorAtPosition(i, R.drawable.ic_tab_item_normal_last, R.color.tab_normal_text_color);
                } else {

                    if (i + 1 == selectedPosition) {
                        setExteriorAtPosition(i, R.drawable.ic_tab_item_normal_pre, R.color.tab_normal_text_color);
                    } else {
                        setExteriorAtPosition(i, R.drawable.ic_tab_item_normal, R.color.tab_normal_text_color);
                    }
                }
            }

            TipView tipView = (TipView) tipContainer.getChildAt(i);
            tipView.setNumber(numbers[i], bottomNumbers[i]);
        }
        tabContainer.postInvalidate();
        tipContainer.postInvalidate();
    }

    private void setExteriorAtPosition(int position, int bgResId, int colorResId) {
        TextView textView = (TextView) tabContainer.getChildAt(position);
        textView.setBackgroundResource(bgResId);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            textView.setTextColor(getContext().getColor(colorResId));
        } else {
            textView.setTextColor(getContext().getResources().getColor(colorResId));
        }
    }

    private TextView createTextView(final String tab, final int position) {
        TextView textView = new TextView(getContext());
        textView.setGravity(Gravity.CENTER);
        textView.setText(tab);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
        textView.getPaint().setFakeBoldText(true);
        textView.setOnClickListener(v -> onSelectChanged(position, tab));
        return textView;
    }

    public void setOnItemSelectedListener(OnItemSelectedListener onItemSelectedListener) {
        this.onItemSelectedListener = onItemSelectedListener;
    }

    public void notifyNumberAlarm(List<SymbolInfo> symbolInfoList) {
        int[] number = new int[tabsData.size()];
        System.arraycopy(numbers, 0, number, 0, number.length);

        int[] bottomNumber = new int[tabsData.size()];
        System.arraycopy(bottomNumbers, 0, bottomNumber, 0, bottomNumber.length);

        for (SymbolInfo info : symbolInfoList) {
            if (EntitiesExtKt.isAlarmWithStatus(info)) {
                String key = info.getMarket() + info.getCurrency() + info.getTransCurrency();
                Long lastTs = lastAlarmTs.get(key);
                if (System.currentTimeMillis() - (lastTs == null ? 0 : lastTs) <= 3000) {
                    // 过滤重复报警 ==> 间隔小于等于15秒的同一个市场同一个交易对报警，不连续累计
                    continue;
                }
                lastAlarmTs.put(key, System.currentTimeMillis());
                int positionByIndex = tabsData.getPositionByIndex(info.getVolumeLevel());
                if (positionByIndex == 0 && !info.isFavorite()) {
                    logger.e("主流+1 >> " + info);
                }
                if (positionByIndex != -1) {
                    if (AlarmTypeConstant.INSTANCE.isBuyType(info.getAlarmH1().getType())) {
                        number[positionByIndex]++;
                    }else {
                        bottomNumber[positionByIndex]++;
                    }
                }
                if (info.isFavorite()) {
//                    number[POSITION_FAVORITE]++;
                    if (AlarmTypeConstant.INSTANCE.isBuyType(info.getAlarmH1().getType())) {
                        number[POSITION_FAVORITE]++;
                    }else {
                        bottomNumber[POSITION_FAVORITE]++;
                    }
                }
                if (info.isAnalysis()) {
//                    number[POSITION_ANALYSIS]++;
                    if (AlarmTypeConstant.INSTANCE.isBuyType(info.getAlarmH1().getType())) {
                        number[POSITION_ANALYSIS]++;
                    }else {
                        bottomNumber[POSITION_ANALYSIS]++;
                    }
                }
            }
        }
        if (selectedPosition > 0 && selectedPosition < number.length) {
            number[selectedPosition] = 0;
        }
        if (selectedPosition > 0 &&  selectedPosition < bottomNumber.length) {
            bottomNumber[selectedPosition] = 0;
        }
        if (number.length >= 0 ) {
            System.arraycopy(number, 0, this.numbers, 0, number.length);
        }
        if ( bottomNumber.length >= 0) {
            System.arraycopy(bottomNumber, 0, this.bottomNumbers, 0, bottomNumber.length);
        }
        refreshAllTabsExterior();
    }

    public interface OnItemSelectedListener {
        void onItemSelected(int position, String tab);
    }
}
